package com.googlecode.keepwalking;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.googlecode.keepwalking.WalkingDetector.WalkingDetectorBinder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.TextView;

public class LogActivity extends Activity {
	private static final String TAG = "LogActivity";
	private static SimpleDateFormat logformat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
	private WalkingDetector detector;
	private boolean fBound = false;
	
	private ServiceConnection sc = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.d(TAG, "onServiceConnected");
			detector = ((WalkingDetectorBinder)service).getService();
			fBound = true;
			showLogs();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.d(TAG, "onServiceDisconnected");
			fBound = false;
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.log);
	}
	
	@Override
	public void onStart() {
		Log.d(TAG, "onStart");
		super.onStart();
		Intent intent = new Intent(this, WalkingDetector.class);
		bindService(intent, sc, BIND_AUTO_CREATE);
	}
	
	@Override
	public void onStop() {
		Log.d(TAG, "onStop");
		super.onStop();
		unbindService(sc);
	}
	
	private void showLogs() {
		TextView tv = (TextView)findViewById(R.id.tvMain);
		Object[] logs = detector.getTracker().getLogs();
		if(logs != null) {
			for(int i = 0; i < logs.length; i++) {
				tv.append(logformat.format(new Date(((WalkingLog)logs[i]).start)));
				tv.append(" ");
				tv.append(logformat.format(new Date(((WalkingLog)logs[i]).end)));
				tv.append("\n");
			}
		}
	}
	
}
